package com.jiang.annotation.aop.cacheable;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class MyCacheableAspect {
    private Map<String, Object> cache = new HashMap<>();

    @Around("@annotation(myCacheable)")
    public Object cacheBefore(ProceedingJoinPoint joinPoint, MyCacheable myCacheable) throws Throwable {
        String cacheName = myCacheable.value();
        if (cache.containsKey(cacheName)) {
            return cache.get(cacheName); // 返回缓存中的值
        } else {
            return joinPoint.proceed(); // 执行方法
        }
    }

    @AfterReturning(pointcut = "@annotation(myCacheable)", returning = "result")
    public void cacheAfterReturning(JoinPoint joinPoint, MyCacheable myCacheable, Object result) {
        String cacheName = myCacheable.value();
        cache.put(cacheName, result); // 缓存值
    }
}

